// 参考数据API服务（等级、类别、行业、地区、人员等）
import axios from 'axios'
import { getCustomerApiUrl } from '@/config/apiConfig'
import { getErrorMessage } from '@/utils/error'

const client = axios.create({
    baseURL: getCustomerApiUrl(),
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' }
})

function norm<T = any>(raw: any): { code: number; message: string; data: T } {
    return {
        code: raw?.code ?? raw?.Code ?? raw?.data?.code ?? raw?.data?.Code ?? 500,
        message: raw?.message ?? raw?.Message ?? raw?.data?.message ?? raw?.data?.Message ?? '',
        // 关键：优先返回最内层的 data
        data: (raw?.data?.data ?? raw?.Data?.Data ?? raw?.data ?? raw?.Data) as T
    }
}

// 将各种返回结构安全转换为数组
function toArray(r: any): any[] {
    if (!r) return []
    const d = r.data ?? r.Data
    if (Array.isArray(d)) return d
    if (Array.isArray(d?.pageData)) return d.pageData
    if (Array.isArray(d?.PageData)) return d.PageData
    if (Array.isArray(d?.data)) return d.data
    if (Array.isArray(d?.Data)) return d.Data
    return []
}

const toNum = (v: any) => (v === null || v === undefined || v === '' ? undefined : Number(v))

export const referenceApi = {
    async getBusinessPartnerLevelById(id: number) {
        const raw = await client.get(`/api/BusinessPartnerLevel/${id}`)
        return norm<any>(raw)
    },
    async getBusinessPartnerCategoryById(id: number) {
        const raw = await client.get(`/api/BusinessPartnerCategory/${id}`)
        return norm<any>(raw)
    },
    async getBusinessNatureById(id: number) {
        const raw = await client.get(`/api/BusinessNature/${id}`)
        return norm<any>(raw)
    },
    async getBusinessPartnerLevelList() {
        const raw = await client.get(`/api/BusinessPartnerLevel/list`, { params: { PageIndex: 1, PageSize: 1000 } })
        return norm<any>(raw)
    },
    async getBusinessPartnerCategoryList() {
        const raw = await client.get(`/api/BusinessPartnerCategory/list`, { params: { PageIndex: 1, PageSize: 1000 } })
        return norm<any>(raw)
    },
    async getBusinessNatureList() {
        const raw = await client.get(`/api/BusinessNature/list`, { params: { PageIndex: 1, PageSize: 1000 } })
        return norm<any>(raw)
    },
    async getAllIndustries() {
        const raw = await client.get(`/api/Industry`)
        return norm<any>(raw)
    },
    async getAllLocations() {
        const raw = await client.get(`/api/Location`)
        return norm<any>(raw)
    },
    async getAllPersons() {
        const raw = await client.get(`/api/Person`)
        return norm<any>(raw)
    },
    // 新增：按ID获取行业/地区/人员
    async getIndustryById(id: number) {
        const raw = await client.get(`/api/Industry/${id}`)
        return norm<any>(raw)
    },
    async getLocationById(id: number) {
        const raw = await client.get(`/api/Location/${id}`)
        return norm<any>(raw)
    },
    async getPersonById(id: number) {
        const raw = await client.get(`/api/Person/${id}`)
        return norm<any>(raw)
    }
}

export type ReferenceLists = {
    levels: Array<{ id: number; levelName: string }>
    categories: Array<{ id: number; categoryName: string }>
    natures: Array<{ id: number; natureName: string }>
    industries: Array<{ id: number; industryName: string }>
    locations: Array<{ id: number; locationName: string }>
    persons: Array<{ id: number; personName: string }>
}

export async function fetchAllReferenceLists(): Promise<ReferenceLists> {
    try {
        const [levelsRes, categoriesRes, naturesRes, industriesRes, locationsRes, personsRes] = await Promise.all([
            referenceApi.getBusinessPartnerLevelList(),
            referenceApi.getBusinessPartnerCategoryList(),
            referenceApi.getBusinessNatureList(),
            referenceApi.getAllIndustries(),
            referenceApi.getAllLocations(),
            referenceApi.getAllPersons()
        ])

        const levels = toArray(levelsRes).map((x: any) => ({ id: x.id ?? x.Id, levelName: x.levelName ?? x.LevelName }))
        const categories = toArray(categoriesRes).map((x: any) => ({ id: x.id ?? x.Id, categoryName: x.categoryName ?? x.CategoryName }))
        const natures = toArray(naturesRes).map((x: any) => ({ id: x.id ?? x.Id, natureName: x.natureName ?? x.NatureName }))
        const industries = toArray(industriesRes).map((x: any) => ({ id: x.id ?? x.Id, industryName: x.industryName ?? x.IndustryName ?? x.name }))
        const locations = toArray(locationsRes).map((x: any) => ({ id: x.id ?? x.Id, locationName: x.locationName ?? x.LocationName ?? x.name }))
        const persons = toArray(personsRes).map((x: any) => ({ id: x.id ?? x.Id, personName: x.personName ?? x.name ?? x.Name }))

        return { levels, categories, natures, industries, locations, persons }
    } catch (e) {
        throw new Error(`加载参考数据失败: ${getErrorMessage(e as any)}`)
    }
}

export async function resolveNamesByIds(ids: { levelId?: number | null; categoryId?: number | null; natureId?: number | null; industryId?: number | null; locationId?: number | null; personId?: number | null; }) {
    const result: Record<string, string | undefined> = {}
    const tasks: Promise<void>[] = []
    try {
        // 这些接口后端存在，保留按ID直查
        if (ids.levelId) tasks.push(referenceApi.getBusinessPartnerLevelById(toNum(ids.levelId)!).then(r => { result.customerLevelName = r.data?.levelName ?? r.data?.LevelName }))
        if (ids.categoryId) tasks.push(referenceApi.getBusinessPartnerCategoryById(toNum(ids.categoryId)!).then(r => { result.customerCategoryName = r.data?.categoryName ?? r.data?.CategoryName }))
        if (ids.natureId) tasks.push(referenceApi.getBusinessNatureById(toNum(ids.natureId)!).then(r => { result.businessNatureName = r.data?.natureName ?? r.data?.NatureName }))

        // 行业/地区/人员：后端无单条接口，用列表匹配，兼容“用编码/工号而非ID”的情况
        const needAny = !!(ids.industryId || ids.locationId || ids.personId)
        if (needAny) {
            const [industries, locations, persons] = await Promise.all([
                referenceApi.getAllIndustries().catch(() => null),
                referenceApi.getAllLocations().catch(() => null),
                referenceApi.getAllPersons().catch(() => null)
            ])
            const industriesArr = industries ? toArray(industries) : []
            const locationsArr = locations ? toArray(locations) : []
            const personsArr = persons ? toArray(persons) : []
            const rawIndustry = ids.industryId as any
            const rawLocation = ids.locationId as any
            const rawPerson = ids.personId as any
            if (ids.industryId != null) {
                const ii = toNum(rawIndustry)
                const code = String(rawIndustry)
                const it = industriesArr.find((x: any) => (
                    (toNum(x.id ?? x.Id) === ii && ii !== undefined) ||
                    (String(x.industryCode ?? x.IndustryCode ?? '') === code)
                ))
                result.industryName = it?.industryName ?? it?.IndustryName ?? it?.name
            }
            if (ids.locationId != null) {
                const ll = toNum(rawLocation)
                const code = String(rawLocation)
                const it = locationsArr.find((x: any) => (
                    (toNum(x.id ?? x.Id) === ll && ll !== undefined) ||
                    (String(x.locationCode ?? x.LocationCode ?? '') === code)
                ))
                result.locationName = it?.locationName ?? it?.LocationName ?? it?.name
            }
            if (ids.personId != null) {
                const pp = toNum(rawPerson)
                const emp = String(rawPerson)
                const it = personsArr.find((x: any) => (
                    (toNum(x.id ?? x.Id) === pp && pp !== undefined) ||
                    (String(x.employeeNumber ?? x.EmployeeNumber ?? '') === emp) ||
                    (String(x.name ?? x.Name ?? '') === emp)
                ))
                result.salesRepresentativeName = it?.personName ?? it?.name ?? it?.Name
            }
        }

        await Promise.all(tasks)
    } catch (e) {
        // 静默失败，返回已有可用字段
    }
    return result
} 